import popEvent from "./event.js";

let temp = document.createElement("template");
document.body.appendChild(temp);
temp.innerHTML = `
<div class="mask">
    <div>标题：{{title}}</div>
    <div>内容：{{content}}</div>
    <div data-hide="true" data-cancel="111">111</div>
    <div data-confirm="222">222</div>
</div>
`;

export default class myCom extends HTMLElement {
  constructor() {
    super();
    console.log(this);
    let attr = this.attributes;
    this._data = {
      title: attr.title ? attr.title.value : "默认的标题",
      content: attr.content ? attr.content.value : "默认的内容",
    };

    this.render();
    this.bindEvent();
    this.compileNode(this.obj);
    this.observe(this._data);

    setTimeout(() => {
      this._data.title = "修改的标题";
    }, 1000);
  }

  render() {
    this.btn = document.createElement("button");
    this.btn.innerHTML = "点击显示弹框";
    this.btn.setAttribute("data-open", "true");
    this.obj = document.createElement("div");
    this.obj.append(temp.content.cloneNode(true));
    this.append(this.obj, this.btn);
    this.hide();
  }

  observe(data) {
    let _this = this;
    this._data = new Proxy(data, {
      set(obj, prop, value) {
        let event = new CustomEvent(prop, {
          detail: value,
        });
        _this.dispatchEvent(event);
        return Reflect.set(...arguments);
      },
    });
  }

  compileNode(el) {
    let child = el.childNodes;
    [...child].forEach((node) => {
      if (node.nodeType === 3) {
        let text = node.textContent;
        let reg = /\{\{\s*([^\s{\}]+)\s*\}\}/g;
        if (reg.test(text)) {
          let $1 = RegExp.$1;
          this._data[$1] &&
            (node.textContent = text.replace(reg, this._data[$1]));

          this.addEventListener($1, (e) => {
            node.textContent = text.replace(reg, e.detail);
          });
        }
      } else if (node.nodeType === 1) {
        let attrs = node.attributes;
        if (attrs.hasOwnProperty("v-model")) {
          let keyname = attrs["v-model"].nodeValue;
          node.value = this._data[keyname];
          node.addEventListener("input", (e) => {
            this._data[keyname] = node.value;
          });
        }

        if (node.childNodes.length > 0) {
          this.compileNode(node);
        }
      }
    });
  }

  bindEvent() {
    this.event = new popEvent({
      obj: this,
    });
  }

  hide() {
    console.log("hide");
    this.obj.style.display = "none";
  }

  open() {
    console.log("open");
    this.obj.style.display = "block";
  }

  cancel() {
    console.log("cancel");
  }

  confirm() {
    console.log("confirm");
  }
}
customElements.define("my-com", myCom);

let style = document.createElement("style");
document.body.appendChild(style);
style.innerText = `
    body{
        margin: 20px;
    }
    .mask{
        background-color: pink;
    }
`;
